#include "client_server.h"
#include "servertcp.h"
#include "sendverificationcode.h"
#include <QtGlobal>
#include "stdlib.h"
Client_Server::Client_Server(TcpSocket *pSock)
{
    this->pSock = pSock;
    innermsglist = new Msg_List();

    connect(pSock,&TcpSocket::sig_getdata,[=]()
    {
        Get_Msg(pSock->Data);
    });
//    pSock->Sock.moveToThread(&this->SockThread);
    this->start(QThread::HighPriority);
}
bool Client_Server::operator == (TcpSocket* pSock)
{
    return pSock == this->pSock;
}
bool Client_Server::operator == (QString uid)
{
    return uid == this->uid;
}
void Client_Server::Get_Msg(QString data)
{
    this->MsgList.push_back(data);
    if(this->state() == Paused)
    {
        this->resume();
    }
}
void Client_Server::Get_innerMsg(Inner_Msg* Msg)
{
    Recive_inner_List.push_back(Msg);
    if(this->state() == Paused)
    {
        this->resume();
    }
}

void Client_Server::process()
{

    if(MsgList.size() == 0 && Recive_inner_List.size() == 0)
        this->pause();
    else
    {
//        if(this->Msg_Block)
//        {

//            return;
//        }
        /*从队列中取出消息*/

        /*先处理内部消息*/
        Task_ForInnerMsg();
        /*处理外部消息*/
        Task_ForOuterMsg();
    }

}
void Client_Server::ClientWrite(QByteArray data)
{
    this->pSock->EnableTrans = 1;
    sleep(1);
    QByteArray temp;
    for(int i = 0;i<data.size();i++)
    {
        if(data[i]!='\\')
        {
            temp = temp + data[i];
        }
    }
    qDebug()<<temp;
    ServerTcp::gethand()->sig_write(this->pSock,data);
}
void Client_Server::Task_ForInnerMsg()
{
    while(Recive_inner_List.size()>0)
    {
        Inner_Msg * pMsg = Recive_inner_List.front();
        Recive_inner_List.pop_front();

        if(pMsg->Msg_Type == "POST_REIGSTER")
        {
            qDebug()<<pMsg->Data["AccountID"];

            if(pMsg->Data["RES"] == "SUCCESS")
            {
                qDebug()<<ProJectData::Get_Download_REIGSTER_Res(true,pMsg->Data["AccountID"]);
                ClientWrite(ProJectData::Get_Download_REIGSTER_Res(true,pMsg->Data["AccountID"]));
            }
            else
            {
                this->pSock->EnableTrans = 1;
                ClientWrite(ProJectData::Get_Download_REIGSTER_Res(false,""));

            }
        }
        if(pMsg->Msg_Type == "LIST_SYNC")
        {
            //sleep(1);
            qDebug()<<pMsg->Data["LIST_SYNC_DATA"];
            ClientWrite(pMsg->Data["LIST_SYNC_DATA"].toUtf8());
        }
        if(pMsg->Msg_Type == "MSG_SYNC")
        {
            qDebug()<<pMsg->Data["MSG_SYNC_DATA"];
            ClientWrite(pMsg->Data["MSG_SYNC_DATA"].toUtf8());
             //send pMsg->Data["MSG_SYNC_DATA"];
        }
        if(pMsg->Msg_Type == "POST_SYNC")
        {
            qDebug()<<pMsg->Data["POST_SYNC_DATA"];
            ClientWrite(pMsg->Data["POST_SYNC_DATA"].toUtf8());
        }
        if(pMsg->Msg_Type =="CREATE_GROUP")
        {
            this->Get_Msg(ProJectData::Get_Upload_LIST_SYNC(uid));
        }
        if(pMsg->Msg_Type == "ADD_TO_GROUP")
        {

        }
        if(pMsg->Msg_Type == "REMOVE_POST")
        {

        }
        if(pMsg->Msg_Type == "ADD_POST")
        {

        }
        if(pMsg->Msg_Type =="LOGIN")
        {
            ProJectData::Get_Download_LOGIN_Res(pMsg->Data["RES"],pMsg->Data["uid"],pMsg->Data["name"],pMsg->Data["passwd"]);
            qDebug()<<"LOGIN RES"<<pMsg->Data["RES"];
            this->uid = pMsg->Data["uid"];
            if(pMsg->Data["RES"] == "LoginSucess")
            {
                Get_Msg(ProJectData::Get_Upload_LIST_SYNC(pMsg->Data["uid"]));

            }
            ClientWrite(ProJectData::Get_Download_LOGIN_Res(pMsg->Data["RES"],pMsg->Data["uid"],pMsg->Data["name"],pMsg->Data["passwd"]));
            sleep(1);
            Get_Msg(ProJectData::Get_Upload_POST_SYNC(uid));
        }
        if(pMsg->Msg_Type == "MSG")
        {

        }

//        emit pMsg->sig_arrived(pMsg);
        this->innermsglist->deletefromlist(pMsg);
    }
}
void Client_Server::Task_ForOuterMsg()
{
    while(MsgList.size()>0)
    {
        qDebug()<<"MsgListsize"<<MsgList.size();
        QString Msg = MsgList.front();
        MsgList.pop_front();
        qDebug()<<Msg;
        qDebug()<<"Size:"<<Msg.size();
        QJsonDocument QJson = QJsonDocument::fromJson(Msg.toUtf8());

        qDebug()<<"end";
        try
        {
            qDebug()<<QJson.object();
            if(QJson.object().contains("Type"))
            {
                qDebug()<<"Type:::::::::::"<<QJson.object().value("Type").toString();
                if(QJson.object().value("Type").toString() == "CHECK")
                {
                    /* 调用API  验证码加入列表*/
                    SendVerificationCode::gethand()->send(QJson.object()["phone_num"].toString(),QString::number(rand()%10000));
                    qDebug()<<QJson.object()["CHECK_NUM"].toString();


                }
                if(QJson.object().value("Type").toString() == "RIGSTER")
                {
                    //Check_Num_Vaild
                    if(SendVerificationCode::gethand()->CheckNumber(QJson.object()["CHECK_NUM"].toString()))
                    {
                        qDebug()<<"RIGSTER";
                        bool Check_Num_Vaild = true;
                        if(Check_Num_Vaild)
                        {
                            Inner_Msg * msg = this->innermsglist->AddNewMsg();

                            msg->PostSQL(this,"POST_REIGSTER","");
                            qDebug()<<QJson.object()["name"].toString();
                            msg->Data.insert("name",QJson.object()["name"].toString());
                            msg->Data.insert("passwd",QJson.object()["passwd"].toString());
                            msg->Data.insert("PhoneNumber",QJson.object()["PhoneNumber"].toString());
                            qDebug()<<QJson.object()["name"].toString();
                            msg->SendToRelay();
                            qDebug()<<QJson.object()["name"].toString();

                        }
                    }

                    else
                    {
                        ProJectData::Get_Download_REIGSTER_Res(false,"");
                    }
                }
                if(QJson.object().value("Type").toString() == "LIST_SYNC")
                {
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"LIST_SYNC","LIST_SYNC");
                    msg->Data.insert("uid",QJson.object()["uid"].toString());
                    msg->SendToRelay();
                }
                if(QJson.object().value("Type").toString() == "MSG_SYNC")
                {
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"MSG_SYNC","MSG_SYNC");
                    msg->Data.insert("GID",QJson.object()["GID"].toString());
                    msg->SendToRelay();
                }
                if(QJson.object().value("Type").toString() == "POST_SYNC")
                {
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"POST_SYNC","POST_SYNC");
                    msg->Data.insert("uid",QJson.object()["uid"].toString());
                    msg->SendToRelay();
                }
                if(QJson.object().value("Type").toString() == "CREATE_GROUP")
                {
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"CREATE_GROUP",""); //1.创建群组（只有发送者 一人） 2. 在  POST里 加入 添加请求

                    msg->Data.insert("uid",uid);
                    qDebug()<<QString(true);

                    msg->Data.insert("IsGroup",QString(QJson.object()["isgroup"].toBool()));
                    msg->SendToRelay();
                }
                if(QJson.object().value("Type").toString() == "PULL_TO_GROUP")
                {
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"PULL_TO_GROUP","POST_SYNC");
                    msg->Data.insert("uid",QJson.object()["uid"].toString());
                    msg->Data.insert("GID",QJson.object()["GID"].toString());
                    msg->SendToRelay();
                }
                if(QJson.object().value("Type").toString() == "ADD_TO_GROUP")
                {
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"ADD_TO_GROUP","POST_SYNC");

                    msg->Data.insert("uid_frind",QJson.object()["uid_frind"].toString());
                    msg->Data.insert("uid",QJson.object()["uid"].toString());
                    msg->Data.insert("GID",QJson.object()["GID"].toString());
                    msg->SendToRelay();
                }
                if(QJson.object().value("Type").toString() == "AGREE_TO_GROUP")
                {
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"AGREE_TO_GROUP","POST_SYNC");
                    msg->Data.insert("uid",QJson.object()["uid"].toString());
                    msg->Data.insert("GID",QJson.object()["GID"].toString());
                    msg->Data.insert("Status",QJson.object()["Status"].toString());

                    msg->SendToRelay();
                }
                if(QJson.object().value("Type").toString() == "APPLY_FRIEND")
                {
                    qDebug()<<"获取申请";
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"APPLY_FRIEND","POST_SYNC");
                    msg->Data.insert("uid",QJson.object()["uid"].toString());
                    msg->Data.insert("uid_friend",QJson.object()["uid_friend"].toString());


                    msg->SendToRelay();
                }
                if(QJson.object().value("Type").toString() == "ADD_FRIEND")
                {

                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"ADD_FRIEND","POST_SYNC");
                    msg->Data.insert("uid",uid);
                    msg->Data.insert("uid_friend",QJson.object()["UID"].toString());
                    msg->Data.insert("Status",QString(QJson.object()["STATUS"].toBool()));

                    msg->SendToRelay();
                }

                if(QJson.object().value("Type").toString() == "LOGIN")
                {
                    //if()验证码验证成功
//                    if(SendVerificationCode::gethand()->CheckNumber(QJson.object()["CHECK_NUM"].toString()))
//                    {
                        Inner_Msg * msg = this->innermsglist->AddNewMsg();
                        msg->PostSQL(this,"LOGIN","");
                        msg->Data.insert("uid",QJson.object()["uid"].toString());

                        qDebug()<<"uid"<<QJson.object()["uid"].toString();
                        qDebug()<<QJson.object()["passwd"].toString();
                        qDebug()<<QJson.object()["IP"].toString();
                        msg->Data.insert("passwd",QJson.object()["passwd"].toString());
                        msg->Data.insert("IP",QJson.object()["IP"].toString());

                        if(QJson.object()["CHECK_NUM"] == "")
                        {
                            msg->Data.insert("IP_CHECK","YES");
                        }
                        else
                        {
                            msg->Data.insert("IP_CHECK","NO");
                        }


                         msg->SendToRelay();
//                    }

//                    else
//                    {
//                        ClientWrite(ProJectData::Get_Download_LOGIN_Res("CHECK_FAILED"));
//                    }

                }
                if(QJson.object().value("Type").toString() == "MSG_UPDATE")
                {

                    ClientWrite(Msg.toUtf8());
                }
                if(QJson.object().value("Type").toString() == "MSG_SEND")
                {
                    Inner_Msg * msg = this->innermsglist->AddNewMsg();
                    msg->PostSQL(this,"MSG_SEND","");
                    msg->Data.insert("GID",QJson.object()["GID"].toString());
                    msg->Data.insert("UID",QJson.object()["UID"].toString());
                    msg->Data.insert("uid_me",this->uid);
                    msg->Data.insert("msg",QJson.toJson());

                    msg->Data.insert("Time",QTime::currentTime().toString());


                    msg->SendToRelay();
                }

            }
        }
        catch (QException e)
        {
// 8276757830
        }

        }

}

































